<template>
	<view class="container">
		<!-- #ifdef MP-WEIXIN -->
		<view v-if="!token" class="force-login-wrap">
			<!-- <image class="logo-bg" src="https://code-app.oss-cn-beijing.aliyuncs.com/jyl/other/108.png" mode="aspectFill"></image> -->
			<!-- <view class="force-login__content y-f">
				<open-data class="user-avatar" type="userAvatarUrl"></open-data>
				<open-data class="user-name" type="userNickName"></open-data>
				<view class="login-notice">为了提供更优质的服务，需要获取您的头像昵称</view>
				!-- <button class="cu-btn author-btn" @getuserinfo="getUserInfo" open-type="getUserInfo">授权并查看</button> --
				<button class="cu-btn author-btn" open-type="getPhoneNumber"
					@getphonenumber="getUserInfo">授权并查看</button>
				<button class="cu-btn close-btn" @tap="back">暂不授权</button>
			</view> -->
		</view>
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<view class="force-login-wrap">
			<image class="logo-bg" src="https://code-app.oss-cn-beijing.aliyuncs.com/jyl/other/108.png" mode="aspectFill">
			</image>
			<view class="force-login__content y-f">
				<view class="login-notice">为了提供更优质的服务，请先登录</view>
				<button class="cu-btn author-btn" @tap="toLogin">快捷登录</button>
				<button style="margin-top: 20rpx;" class="cu-btn author-btn" @tap="loginFun">账号密码登录</button>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from "vuex";
	import cookie from "@/utils/cookie/cookie.js";
	import {
		login,
		appLogin
	} from "@/utils";

	export default {
		data() {
			return {
				univerifyManager: null,
				isWeixin: false
			};
		},
		computed: {
			...mapState(["isAuthorization", "$deviceType", "token"]),
		},
		mounted() {
			// #ifdef  APP-PLUS
			if (plus.runtime.isApplicationExist({
					pname: 'com.tencent.mm',
					action: 'weixin://'
				})) {
				//安装微信后的逻辑
				this.isWeixin = true
			} else {
				this.isWeixin = false
			}
			// #endif
		},
		onHide() {
			this.updateAuthorizationPage(false);
			this.changeAuthorization(false);
		},
		onUnload() {
			this.updateAuthorizationPage(false);
			this.changeAuthorization(false);
		},
		methods: {
			...mapActions(["changeAuthorization", "setUserInfo"]),
			...mapMutations(["updateAuthorizationPage"]),
			loginFun() {
				this.$yrouter.push({
					path: "/userPack/pages/user/Login/index"
				});
			},
			toLogin() {
				const self = this
				self.univerifyManager = uni.getUniverifyManager()
				// 预登录
				self.univerifyManager.preLogin()
				// 调用一键登录弹框
				const univerifyStyle = {
					"fullScreen": true,
					"buttons": {
						"iconWidth": "45px",
						"list": []
					}
				}
				console.log(univerifyStyle)
				if (this.isWeixin) {
					univerifyStyle.buttons.list.push({
						"provider": "weixin",
						"iconPath": "/static/image/wechat.png"
					})
				}
				// #ifdef APP-IOS
				univerifyStyle.buttons.list.push({
					"provider": "apple",
					"iconPath": "/static/image/apple.png"
				})
				// #endif
				self.univerifyManager.login({
					univerifyStyle,
					success(res) {
						console.log('login success', res)
						// 调用后端api
						// 在得到access_token后，通过callfunction调用云函数
						uniCloud.callFunction({
							name: 'getPhoneNumber', // 你的云函数名称
							data: {
								'access_token': res.authResult.access_token, // 客户端一键登录接口返回的access_token
								'openid': res.authResult.openid // 客户端一键登录接口返回的openid
							}
						}).then(data => {
							console.log(data)
							appLogin({
								phone: data.result.data.phoneNumber,
								type: 'oneClickLogin'
							}).then(res => {
								console.log(res)
								self.univerifyManager.close()
								// 取消订阅自定义按钮点击事件
								self.univerifyManager.offButtonsClick(self.buttonsCallback)
								self.univerifyManager = null
								// 分类型做跳转
								self.$yrouter.reLaunch({
									// path: cookie.get("redirect").replace(/\ /g, ''),
									path: '/pages/launch/index',
									query: {
										type: 'User'
									}
								});
							}).catch((error) => {
								uni.showToast({
									title: error,
									icon: "none",
									duration: 2000,
								});
							});
						}).catch(err => {
							// 处理错误
						})
					}
				})

				// 订阅自定义按钮点击事件
				self.univerifyManager.onButtonsClick(self.buttonsCallback)
			},
			buttonsCallback(res) {
				const self = this
				console.log(res)
				// if (res.result) {
				//  // 获取一键登录弹框协议勾选状态
				//  univerifyManager.getCheckBoxState({
				//    success(res) {
				//      console.log("getCheckBoxState res: ", res);
				//      if (res.state) {
				//        // 关闭一键登录弹框
				//        // univerifyManager.close()
				//      }
				//    }
				//  })
				// }
				// 苹果授权登录
				if (res.provider == 'apple') {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (res.provider.indexOf('apple')) {
								uni.login({
									provider: 'apple',
									success: function(loginRes) {
										console.log(loginRes)
										appLogin({
											type: 'appleLogin',
											identityToken: loginRes.authResult.access_token
										}).then(_res => {
											if (!_res) {
												self.$yrouter.reLaunch({
													path: "/userPack/pages/user/BindingPhone/index",
													query: {
														identityToken: loginRes
															.authResult
															.access_token
													}
												});
											}
											self.univerifyManager.close()
											// 取消订阅自定义按钮点击事件
											self.univerifyManager.offButtonsClick(self
												.buttonsCallback)
											self.univerifyManager = null
										}).catch((error) => {
											uni.showToast({
												title: error,
												icon: "none",
												duration: 2000,
											});
										});
									}
								});
							}
						}
					})
				}
				// 微信授权登录
				if (res.provider == 'weixin') {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (res.provider.indexOf('weixin')) {
								uni.login({
									provider: 'weixin',
									onlyAuthorize: true,
									success: function(loginRes) {
										console.log(loginRes.code)
										appLogin({
											type: 'wx',
											code: loginRes.code
										}).then(_res => {
											// 没有绑定手机号码或者新用户首次授权
											if (!_res) {
												self.$yrouter.reLaunch({
													path: "/userPack/pages/user/BindingPhone/index",
													query: {
														code: loginRes.code
													}
												});
											}
											self.univerifyManager.close()
											// 取消订阅自定义按钮点击事件
											self.univerifyManager.offButtonsClick(self
												.buttonsCallback)
											self.univerifyManager = null
										}).catch((error) => {
											uni.showToast({
												title: error,
												icon: "none",
												duration: 2000,
											});
										});
									}
								});
							}
						}
					})
				}
			},
			back() {
				this.$yrouter.reLaunch({
					path: "/pages/launch/index"
				});
			},
			// getUserInfo(e) {
			// 	cookie.set("encryptedUserInfoData", e.mp.detail.encryptedData);
			// 	cookie.set("ivUserInfo", e.mp.detail.iv);
			// 	if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
			// 		uni.showToast({
			// 			title: '已取消授权登录',
			// 			icon: 'none'
			// 		})
			// 		return
			// 	}
			// 	uni.showLoading({
			// 		title: "登录中",
			// 	});
			// 	login().then((res) => {
			// 		console.log('重定向')
			// 		this.$yrouter.reLaunch({
			// 			path: cookie.get("redirect").replace(/\ /g, '')
			// 		});
			// 	}).catch((error) => {
			// 		console.log(error);
			// 		uni.showToast({
			// 			title: error,
			// 			icon: "none",
			// 			duration: 2000,
			// 		});
			// 	});
			// },
		}
	};
</script>

<style lang="less">
	.container {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		position: relative;
	}

	.force-login-wrap {
		width: 100%;
		height: 100%;
		overflow: hidden;
		z-index: 11111;
		top: 0;
		padding-top: 200rpx;
		text-align: center;

		.logo-bg {
			width: 100rpx;
			height: 100rpx;
			margin-bottom: 44rpx;
			border-radius: 50%;
		}

		.force-login__content {

			.user-avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				overflow: hidden;
				margin-bottom: 40rpx;
			}

			.user-name {
				font-size: 35rpx;
				font-weight: bold;
				color: #000;
				margin-bottom: 30rpx;
			}

			.login-notice {
				font-size: 28rpx;
				font-weight: 400;
				color: #000;
				line-height: 44rpx;
				width: 500rpx;
				text-align: center;
				margin: 0 auto 80rpx;
			}

			.author-btn {
				width: 630rpx;
				height: 80rpx;
				// background: linear-gradient(to right, #f35447 0%, #ff8e3c 100%);
				// background: -moz-linear-gradient(to right, #f35447 0%, #ff8e3c 100%);
				background-color: #00B78A;
				// box-shadow: 0px 7rpx 6rpx 0px rgba(229, 138, 0, 0.22);
				border-radius: 40rpx;
				font-size: 30rpx;
				font-weight: 500;
				color: rgba(255, 255, 255, 1);
			}

			.close-btn {
				width: 630rpx;
				height: 80rpx;
				margin-top: 30rpx;
				border-radius: 40rpx;
				border: 2rpx solid #00B78A;
				background: none;
				font-size: 30rpx;
				font-weight: 500;
				color: #00B78A;
			}
		}
	}
</style>